from django.test import TestCase
import datetime
import json
import re
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.views import View

# Create your views here.
from lhc_order.models import Order
from test_xianghaiyang.models import House
from xiejian_user.models import User

class AddOrder(View):
    """添加订单"""

    def post(self, request):

        # # 判断用户是否登录
        # if not request.user.is_authenticated:
        #     return JsonResponse({'errno': "4101",
        #                          'errmsg': '用户未登录'})
        #
        # # 接收参数
        # json_dict = json.loads(request.body.decode())
        # house_id = json_dict.get('house_id')
        # start_date = json_dict.get('start_date')
        # end_date = json_dict.get('end_date')
        #
        # # 判断参数是否齐全
        # if not all([house_id, start_date, end_date]):
        #     return JsonResponse({'errno': "4103",
        #                          'errmsg': '缺少必传参数'})

        # house_id校验
        # try:
        #     House.objects.get(id=house_id)
        # except Exception as e:
        #     return JsonResponse({'errno': "4001",
        #                          'errmsg': '房源查询错误'})

        # start_date校验
        # data_start = datetime.datetime.strptime(start_date,"%Y-%m-%d")
        # data_end = datetime.datetime.strptime(end_date,"%Y-%m-%d")
        # if data_end < data_start:
        #     return JsonResponse({'errno': "4103",
        #                          'errmsg': '时间格式错误'})

        # 订单保存到数据库
        # 获取登录用户id
        # user = request.user.id
        user = 4

        # 预订天数
        # days = data_end - data_start

        try:
            # 房屋单价
            house_price = House.objects.get(id=5).price


        except Exception as e:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '获取房屋单价出错'})


        try:
            # 保存订单基本信息 Order
            order = Order.objects.create(
                user=user,
                house=5,
                begin_date=2020-5-13,
                end_date=2020-5-16,
                days=4,
                house_price=house_price,
                amount=4 * house_price,
            )
            res = Order.objects.count(house=5)
            house=House.objects.filter(id=5,
                                       order_count=0).update(order_count=res)

        except Exception as e:
            return JsonResponse({'errno': '4004',
                                 'errmsg': '保存订单出错'})

        # 保存订单
        order.save()
        house.save()